import React, { Children, useEffect, useRef, useMemo } from "react"
import { CommonComponenetProps } from "../../interface"
import { useDrag } from "react-dnd"
import { useMaterialDrop } from "../../hooks/useMaterialDrop"
import { Form as AntdForm , Input} from "antd"

const Form = ({id, name, children, onFinish }: CommonComponenetProps) => {

    const divRef = useRef<HTMLDivElement|null>(null)
    
    const [form] = AntdForm.useForm()

    const [, drag] = useDrag(() => ({
        type: name,
        item: {
            type: name,
            dragType: "move",
            id: id,
        }
    }))

    const { canDrop, drop } = useMaterialDrop(["FormItem"], id)

    useEffect(() => {
        drag(divRef)
        drop(divRef)
    },[])

    const formItems = useMemo(() => {
        return React.Children.map(children, (item: any) => ({
            id: item.props?.id,
            type: item.props?.type,
            name: item.props?.name,
            label: item.props?.label,
        }))
    }, [children])

    return (
        <div
            className={`w-[100%] p-[20px] min-h-[100px] ${canDrop ? 'border-[2px] border-[blue]' : 'border-[1px] border-[#000]'}`}
            ref={divRef}
            data-component-id={id}
        >
            <AntdForm
                labelCol={{ span: 6 }} 
                wrapperCol={{ span: 18 }} 
                form={form}
                onFinish={() => {
                    onFinish && onFinish(form)
                }}
            >
                {formItems?.map((item: any) => {
                    return (
                        <AntdForm.Item
                            data-component-id={item.id}
                            key={item.name}
                            name={item.name}
                            label={item.label}
                        >
                            <Input style={{pointerEvents: 'none'}}/>
                        </AntdForm.Item>
                    )
                })}
            </AntdForm>
        </div>
    )
}

export default Form